package com.heng.groupchat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heng.groupchat.common.StatusCode;
import com.heng.groupchat.exception.BusinessException;
import com.heng.groupchat.mapper.UserMapper;
import com.heng.groupchat.model.entity.User;
import com.heng.groupchat.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户服务实现类
 *
 * @author faye
 * @description 针对表 user 的数据库操作 Service
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户注册
     *
     * @param username   用户账户
     * @param password  用户密码
     * @param checkPassword 校验密码
     * @return 新用户 id
     */
    @Override
    public long userRegister(String username, String password, String checkPassword) {
        // 密码和校验密码相同
        if (!password.equals(checkPassword)) {
            throw new BusinessException(StatusCode.PARAMS_ERROR, "密码与校验密码不一致");
        }
        // 账户不能重复
        User user = this.getUserByUsername(username);
        if (user != null) {
            throw new BusinessException(StatusCode.PARAMS_ERROR, "账号已存在");
        }
        // 插入
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        boolean saveResult = this.save(newUser);
        if (!saveResult) {
            throw new BusinessException(StatusCode.SYSTEM_ERROR, "数据库错误");
        }
        return newUser.getId();
    }

    @Override
    public User getUserByUsername(String username) {
        if(username == null) {
            throw new BusinessException(StatusCode.PARAMS_NULL_ERROR, "账户为空！");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }

    /**
     * 获取当前登录用户
     *
     * @param request HTTP请求
     * @return 当前登录用户
     */
    @Override
    public User getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute("USER_LOGIN_STATE");
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(StatusCode.LOGIN_ERROR, "未登录");
        }
        return currentUser;
    }
}